package com.company.clientscard.shared.proxyManager;

import java.util.List;

import com.company.clientscard.shared.proxy.ClientProxy;
import com.company.clientscard.shared.requestfactory.ClientsRequestFactory;
import com.company.clientscard.shared.requestfactory.ClientsRequestFactory.ClientRequestContext;
import com.google.gwt.core.client.GWT;
import com.google.gwt.view.client.HasData;
import com.google.web.bindery.event.shared.SimpleEventBus;
import com.google.web.bindery.requestfactory.shared.Receiver;

public class ClientProxyManager implements ProxyManager<ClientProxy> {

	private ClientRequestContext context;

	public void refreshDisplays(HasData<ClientProxy> display) {
		display.setVisibleRangeAndClearData(display.getVisibleRange(), true);
	}

	public void initContext() {
		ClientsRequestFactory factory = GWT.create(ClientsRequestFactory.class);
		factory.initialize(new SimpleEventBus());
		context = factory.context();
	}

	public ClientProxy getProxyObject() {
		initContext();
		ClientProxy client = context.create(ClientProxy.class);
		return client;
	}

	public void add(ClientProxy object, final HasData<ClientProxy> display) {
		context.save(object).with("code, name").fire(new Receiver<Void>() {

			@Override
			public void onSuccess(Void response) {
				refreshDisplays(display);
			}
		});

	}

	public void update(ClientProxy object, final HasData<ClientProxy> display) {
		context.update(object).fire(new Receiver<ClientProxy>() {

			@Override
			public void onSuccess(ClientProxy response) {
				refreshDisplays(display);
			}
		});
	}

	@Override
	public void setObjectList(final int firstRow, int numberOfRows,
			final HasData<ClientProxy> display) {
		initContext();
		context.findAll(firstRow, numberOfRows).fire(
				new Receiver<List<ClientProxy>>() {

					@Override
					public void onSuccess(List<ClientProxy> response) {
						// TODO Auto-generated method stub
						display.setRowData(firstRow, response);

					}
				});
	}

	@Override
	public ClientProxy getProxyObject(ClientProxy object) {
		initContext();
		ClientProxy editibleObject = context.edit(object);
		return editibleObject;
	}
}
